import { useEffect, useState } from 'react';
import PropTypes from 'prop-types'; // 引入 PropTypes
import { Table, Button, Modal, Upload, message, Form, Input, Breadcrumb, Popconfirm } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
// import axios from 'axios';
import { adManagement } from '../../../../apis/auth';
import './content.less';

const AdManagement = ({ isAdding, setIsAdding }) => {
    const [ads, setAds] = useState([]);
    const [loading, setLoading] = useState(false);
    const [uploading, setUploading] = useState(false);
    const [selectedAd, setSelectedAd] = useState(null);

    useEffect(() => {
        fetchAds();
    }, []);
  //获取广告
    const fetchAds = async () => {
        setLoading(true);
        try {
            const response = await adManagement.getAllAds();
            setAds(response.data.data);
        } catch (error) {
            message.error('获取广告失败');
        } finally {
            setLoading(false);
        }
    };
  // 删除广告
    const handleDeleteAd = async (id) => {
        try {
            await adManagement.deleteAd(id);
            message.success('广告删除成功');
            fetchAds();
        } catch (error) {
            message.error('广告删除失败');
        }
    };
  // 更改一级页面中图片，将选择的图片信息进行传入
    const handleChangeImage = (ad) => {
        setSelectedAd(ad);
    };
 //更改一级页面中的图片
    const handleUpload = async ({ file }) => {
        setUploading(true);
        try {
            await adManagement.changeAdPictures(selectedAd.id, file);
            message.success('图片上传成功');
            fetchAds();
        } catch (error) {
            message.error('图片上传失败');
        } finally {
            setUploading(false);
            setSelectedAd(null);
        }
    };
//一级页面显示
    const columns = [
        {
            title: '广告公司',
            dataIndex: 'adCompany',
            key: 'adCompany',
        },
        {
            title: '广告名称',
            dataIndex: 'adName',
            key: 'adName',
        },
        {
            title: '所属分类',
            dataIndex: 'adCategory',
            key: 'adCategory',
        },
        {
            title: '广告图片',
            dataIndex: 'file',
            key: 'file',
            render: (text) => <img src={text} alt="ad" style={{ width: 100 }} />,
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <>
                    <Button type="primary" onClick={() => handleChangeImage(record)}>更改图片</Button>
                    <Popconfirm
                        title="确定要删除这个广告吗？"
                        onConfirm={() => handleDeleteAd(record.id)}
                        okText="是"
                        cancelText="否"
                    >
                        <Button type="danger" style={{ marginLeft: 8, backgroundColor: 'red', color: 'white' }}>删除广告</Button>
                    </Popconfirm>
                </>
            ),
        },
    ];
  //新增广告
    const handleAddAd = async (values) => {
        const { adCategory, adCompany, adName, file } = values;
        console.log('handleAddAd values:', values); // 调试日志  不加下面的话发现虽然params正常传递但是，file显示传递是数组，因此需要从file数组中提取originFileObj 作为文件对象传递给 adManagement.addAd 函数。

        const fileObject = file[0].originFileObj; // 获取文件对象
        try {
            await adManagement.addAd(adCategory, adCompany, adName, fileObject);
            message.success('广告新增成功');
            setIsAdding(false);
            fetchAds();
        } catch (error) {
            message.error('广告新增失败');
        }
    };

    if (isAdding) {
        return (
            <div>      
                <Breadcrumb 
                items={[
                    {
                        title: '广告投放管理',
                    },
                    {
                        title: '新增广告',
                    }
                ]}
                />
                <Form layout="vertical" onFinish={handleAddAd} style={{ marginTop: 16 }}>
                    <Form.Item
                        name="adCompany"
                        label="广告公司"
                        rules={[{ required: true, message: '请输入广告公司名称' }]}
                    >
                     <Input />
                    </Form.Item>
                    <Form.Item
                        name="adName"
                        label="广告名称"
                        rules={[{ required: true, message: '请输入广告名称' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="adCategory"
                        label="所属分类"
                        rules={[{ required: true, message: '请输入广告分类' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="file"
                        label="上传广告图片"
                        valuePropName="fileList"
                        getValueFromEvent={(e) => {
                            if (Array.isArray(e)) {
                                return e;
                            }
                            return e && e.fileList;
                        }}
                        rules={[{ required: true, message: '请上传广告图片' }]}
                    >
                        <Upload beforeUpload={() => false}>
                            <Button icon={<UploadOutlined />}>选择图片</Button>
                        </Upload>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">提交</Button>
                        <Button onClick={() => setIsAdding(false)} style={{ marginLeft: 8 }}>取消</Button>
                    </Form.Item>
                </Form>
            </div>
        );
    }

    return (
        <>
            <Table columns={columns} dataSource={ads} rowKey="id" loading={loading} style={{ marginTop: 16 }} />
            <Modal
                title="更改广告图片"
                open={!!selectedAd}
                onCancel={() => setSelectedAd(null)}
                footer={null}
            >
                <Upload
                    customRequest={handleUpload}
                    showUploadList={false}
                >
                    <Button icon={<UploadOutlined />} loading={uploading}>上传新图片</Button>
                </Upload>
            </Modal>
        </>
    );
};

// 为 AdManagement 组件添加 prop 类型验证
AdManagement.propTypes = {
    isAdding: PropTypes.bool,
    setIsAdding: PropTypes.func,
};

export default AdManagement;
